package com.base.cn.platform.os.service.course.comment;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.course.comment.CourseCommentDao;
import com.base.cn.platform.os.entity.course.catalog.CourseCatalog;
import com.base.cn.platform.os.entity.course.comment.CourseComment;
import com.base.cn.platform.os.entity.course.cou.Course;
import com.base.cn.platform.os.entity.course.cou.CourseProfile;
import com.base.cn.platform.os.service.course.catalog.CourseCatalogBiz;
import com.base.cn.platform.os.service.course.cou.CourseBiz;
import com.base.cn.platform.os.service.course.cou.CourseProfileBiz;
import com.base.cn.platform.os.service.manage.user.user.SetUserDataService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 课程评论
 *
 * @author SK
 * @since 2018-06-08
 */
@Service
public class CourseCommentBiz extends BaseBiz<CourseComment, CourseCommentDao> {

    @Autowired
    private CourseBiz courseBiz;
    @Autowired
    private CourseCatalogBiz courseCatalogBiz;
    @Autowired
    private CourseProfileBiz courseProfileBiz;
    @Autowired
    private SetUserDataService<CourseComment> setUserDataService;

    /**
     * 查找课程评论列表
     *
     * @param comment 课程评论
     * @return 课程评论列表
     */
    public List<CourseComment> findCourseCommentList(CourseComment comment, boolean setCreator,
                                                     boolean setCourse, boolean setCatalog) {
        String where = this.where(comment);
        List<CourseComment> commentList = find(where, null, null);
        this.setCourseCommentCourse(commentList, setCourse);
        this.setCourseCommentCatalog(commentList, setCatalog);
        setUserDataService.setUserData(commentList, setCreator);
        return commentList;
    }

    /**
     * 查找课程评论列表
     *
     * @param comment 课程评论
     * @return 课程评论列表
     */
    public PageInfo<CourseComment> findCourseCommentPage(CourseComment comment, Pagination pagination,
                                                         boolean setCreator, boolean setCourse, boolean setCatalog) {
        String where = this.where(comment);
        PageInfo<CourseComment> pageInfo = findPage(where, pagination, null);
        this.setCourseCommentCourse(pageInfo.getList(), setCourse);
        this.setCourseCommentCatalog(pageInfo.getList(), setCatalog);
        setUserDataService.setUserData(pageInfo.getList(), setCreator);
        return pageInfo;
    }

    /**
     * 保存课程评价
     *
     * @param courseComment 课程评价
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public void saveCourseComment(CourseComment courseComment) {
        //设置平均分
        courseComment.calculateMultiple();
        courseComment.setBefore(null);
        save(courseComment);
        //获取目录对象
        CourseCatalog catalog = courseCatalogBiz.findById(courseComment.getCatalogId());
        catalog.setCommentCount(catalog.getCommentCount() + 1);//累加评论量
        catalog.setQuality(catalog.getQuality() + courseComment.getQuality());//累加总分
        catalog.setTeach(catalog.getTeach() + courseComment.getTeach());//累加总分
        catalog.setFeel(catalog.getFeel() + courseComment.getFeel());//累加总分
        courseCatalogBiz.updateById(catalog, null);
        //更新课程评论数据
        CourseProfile profile = courseProfileBiz.findById(courseComment.getCourseId());
        profile.setCommentCount(profile.getCommentCount() + 1);
        profile.addQuality(courseComment.getQuality());
        profile.addTeach(courseComment.getTeach());
        profile.addFeel(courseComment.getFeel());
        profile.calculateMultiple();
        courseProfileBiz.updateById(profile, null);
    }

    /**
     * 设置评论的目录数据
     * @param commentList 评论列表
     * @param setCatalog 是否设置目录数据
     */
    private void setCourseCommentCatalog(List<CourseComment> commentList, boolean setCatalog) {
        if (setCatalog && ObjectUtils.isNotEmpty(commentList)) {
            String catalogIds = DataUtil.joining(commentList, CourseComment::getCatalogId);
            List<CourseCatalog> catalogList = courseCatalogBiz.findCourseCatalogByIds(catalogIds, false, false, false, false);
            Map<BigDecimal, CourseCatalog> catalogMap = DataUtil.toMap(catalogList, CourseCatalog::getId);
            commentList.forEach((v) -> v.setCatalog(catalogMap.get(v.getCatalogId())));
        }
    }

    /**
     * 设置评论的目录数据
     * @param commentList 评论列表
     * @param setCourse 设置评论课程
     */
    private void setCourseCommentCourse(List<CourseComment> commentList, boolean setCourse) {
        if (setCourse && ObjectUtils.isNotEmpty(commentList)) {
            String courseIds = DataUtil.joining(commentList, CourseComment::getCourseId);
            Map<BigDecimal, Course> courseMap = courseBiz.findCourseToMapByIds(courseIds, false, false, false);
            commentList.forEach((v) -> v.setCourse(courseMap.get(v.getCourseId())));
        }
    }

    /**
     * 查询条件
     * @param comment
     * @return
     */
    private String where(CourseComment comment) {
        StringBuilder where = new StringBuilder(" 1=1");
        if (DataUtil.idIsNotNull(comment.getCourseId())) {
            where .append( " and courseId = " ).append( comment.getCourseId());
        }
        if (DataUtil.idIsNotNull(comment.getCatalogId())) {
            where .append( " and catalogId = " ).append( comment.getCatalogId());
        }
        if (DataUtil.idIsNotNull(comment.getUserId())) {
            where .append( " and userId = " ).append( comment.getUserId());
        }
        if (DataUtil.isPositive(comment.getStatus())) {
            where .append( " and status = " ).append( comment.getStatus());
        }
        where .append(" order by id desc");
        return where.toString();
    }

    /**
     * @param ids 评价id串
     * @param setCreator 设置评论人的数据
     * @param setCourse 设置评论课程设置评论课程
     * @param setCatalog 设置评论的目录数据
     * @return
     */
    public List<CourseComment> ExcelDetailList(String ids, boolean setCreator,
                                                     boolean setCourse, boolean setCatalog,Map<String,Object> param) {
        StringBuilder where = new StringBuilder(" 1=1");
        if(ObjectUtils.isNotEmpty(param.get("id"))){
            where .append( " and catalogId=").append(param.get("id"));
        }
        if(ObjectUtils.isNotEmpty(param.get("courseId"))){
            where .append( " and courseId=").append(param.get("courseId"));
        }
        if (StringUtils.isNotEmpty(ids)) {
            where.append("  and id in (").append(ids).append(")");
        }
        if(ObjectUtils.isNotEmpty(param.get("beginCommentTime"))){
            where.append(  "  and createTime>= '").append(param.get("beginCommentTime").toString()).append("'");
        }
        if(ObjectUtils.isNotEmpty(param.get("endPayCommentTime"))){
            where.append(  "  and createTime<= '").append(param.get("endPayCommentTime").toString()).append("'");
        }
        if(ObjectUtils.isNotEmpty(param.get("gainDay"))){
            where .append("  and createTime >='").append( DateUtils.format(DateUtils.getPastDate(Integer.valueOf(param.get("gainDay").toString())==1?7:30) ,"yyyy-MM-dd")).append("'");
        }
        List<CourseComment> commentList = find(where.toString(), null, null);
        setCourseCommentCourse(commentList, setCourse);
        setCourseCommentCatalog(commentList, setCatalog);
        setUserDataService.setUserData(commentList, setCreator);
        return commentList;
    }

    /**
     *获取评论数
     * @param comment 查询条件
     * @return
     */
    public BigDecimal findCommentCount(CourseComment comment){
        String where = this.where(comment);
        return this.count(where);
    }
}
